<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"/>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKey"
      :allow-drop="allowDrop"
      :draggable="draggable"
      @node-drop="handleDrop"
      node-key="catId"
      show-checkbox
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{node,data}">
        <span>{{node.label}}</span>
        <span>
          <el-button v-if="node.level<=2" type="text" size="mini"
                     @click="()=>append(data)">Append</el-button>
          <el-button type="text" size="mini"
                     @click="()=>edit(data)">edit</el-button>
          <el-button v-if="node.childNodes.length===0" type="text" size="mini"
                     @click="()=>remove(node, data)">Delete</el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      width="30%"
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitData">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'category',
    data () {
      return {
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        menus: [],
        expandedKey: [],
        dialogVisible: false,
        category: {
          name: '',
          parentCid: '',
          showStatus: 1,
          catLevel: null,
          sort: 0,
          catId: null,
          productUnit: '',
          icon: ''
        },
        dialogType: '', // edit,add
        title: '',

        // 拖拽相关
        maxLevel: 0,
        uploadNodes: [],
        draggable: false,
        pCid: {}

      }
    },
    methods: {
      // 获取数据列表
      getMenus () {
        this.$http({
          url: this.$http.adornUrl('/product/category/list/tree'),
          method: 'get'
        }).then(({data}) => {
          this.menus = data.data
        })
      },

      batchDelete () {
        const checkedNodes = this.$refs.menuTree.getCheckedNodes()
        const catIds = []
        const catNameArr = []
        for (let i = 0; i < checkedNodes.length; ++i) {
          catIds.push(checkedNodes[i].catId)
          catNameArr.push(checkedNodes[i].name)
        }

        this.$confirm(`是否批量删除【${catNameArr.join(',')}】菜单?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(catIds, false)
          }).then(({data}) => {
            this.$message({
              message: '菜单删除成功',
              type: 'success'
            })

            // 刷新出新的菜单
            this.getMenus()
          })
        })
          .catch(() => {

          })
      },

      batchSave () {
        if (this.uploadNodes.length === 0) return

        this.$http({
          url: this.$http.adornUrl('/product/category/update/sort'),
          method: 'post',
          data: this.$http.adornData(this.uploadNodes, false)
        }).then(({data}) => {
          this.$message({
            message: '菜单排序修改成功',
            type: 'success'
          })

          // 刷新菜单数据
          this.getMenus()
          // 设置需要默认展开的菜单
          this.expandedKey = Object.values(this.pCid)
          // 清空
          this.uploadNodes = []
          this.pCid = {}
        })
      },

      // 拖拽成功时触发的回调(即allowDrop为true时)
      handleDrop (draggingNode, dropNode, dropType, ev) {
        console.log('handleDrop', draggingNode, dropNode, dropType)
        let pCid = 0 // 拖拽完成后 当前节点最新的父节点id
        let siblings = null // 拖拽完成后 同一层级的所有准备重新排序的节点

        /**
         注意：
             在elm中 你把一个节点拖进 一个没打开的父节点 和 一个打开的父节点
             属于不同的dropType
             前者为inner  后者为 before 或则 after

             并且此时handleDrop接受到的dropNode是不同的
             前者为那个没有打开的父节点 后者为被拖拽节点最终放置的位置(节点)
        */

        if (dropType === 'before' || dropType === 'after') {
          pCid = dropNode.parent.data.catId || 0 /* ← elm的tree接受的是一个数组,这个数组中的每个成员对应一个node,在这些【根】node之上还有一个node,这个node则是我们传递的数组(即.parent的尽头) */
          siblings = dropNode.parent.childNodes
        } else {
          dropNode.expanded = true
          pCid = dropNode.data.catId
          siblings = dropNode.childNodes
        }

        this.pCid[draggingNode.data.cid] = pCid

        // 收集拖拽结果数据
        // 1. 对当前节点同一层级的所有节点进行排序 并收集最新的排序
        // 2. 计算当前节点及其后代节点的最新catLevel 并收集
        // 3. 收集当前节点最新的pCid
        for (let i = 0; i < siblings.length; ++i) {
          if (siblings[i].data.catId === draggingNode.data.catId) {
            let catLevel = draggingNode.level
            if (siblings[i].level !== draggingNode.level) {
              // 修改当前以及后代节点的catLevel
              catLevel = siblings[i].level
              this.updateChildNodeLevel(siblings[i])
            }
            this.uploadNodes.push({catId: siblings[i].data.catId, sort: i, parentCid: pCid, catLevel: catLevel})
          } else {
            this.uploadNodes.push({catId: siblings[i].data.catId, sort: i})
          }
        }

        // 本次拖拽变更的数据
        console.log('updateNodes', this.uploadNodes)
      },

      updateChildNodeLevel (node) {
        if (node.childNodes.length > 0) {
          for (let i = 0; i < node.childNodes.length; ++i) {
            const cNode = node.childNodes[i].data
            this.uploadNodes.push({catId: cNode.catId, catLevel: node.childNodes[i].level})
            this.updateChildNodeLevel(node.childNodes[i])
          }
        }
      },

      // 层级不得大于3
      allowDrop (draggingNode, dropNode/* ←targetNode */, type) {
        console.log('allowDrop', draggingNode, dropNode, type)
        this.countNodeLevel(draggingNode)

        const deep = (this.maxLevel - draggingNode.level) + 1 // 当前拖动节点一共有几层(包括本身,比如它有一层儿子,那么深度就是2层)

        // 清空
        this.maxLevel = 0

        if (type === 'inner') {
          return (deep + dropNode.level) <= 3
        } else {
          return (deep + dropNode.parent.level) <= 3
        }
      },

      countNodeLevel (node) {
        // 找到所有子节点,求出最大深度
        if (node.childNodes != null && node.childNodes.length > 0) {
          for (let i = 0; i < node.childNodes.length; ++i) {
            if (node.childNodes[i].level > this.maxLevel) {
              this.maxLevel = node.childNodes[i].level
            }
            this.countNodeLevel(node.childNodes[i])
          }
        }
      },

      // @node-drag-enter="handleDragEnter"
      // handleDragEnter (draggingNode, dropNode, ev) {
      //   dropNode.expanded = true
      // },
      // @node-drag-leave="handleDragLeave"
      // todo 貌似只要进入父节点后,然后往下移到这个父节点的第一个子节点就算离开了
      // handleDragLeave (draggingNode, dropNode, ev) {
      //   dropNode.expanded = false
      // },

      edit (data) {
        this.dialogType = 'edit'
        this.title = '修改分类'
        this.dialogVisible = true

        // 发送请求获取当前节点最新的数据
        this.$http({
          url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
          method: 'get'
        }).then(({data: {data}}) => {
          this.category.name = data.name
          this.category.catId = data.catId
          this.category.icon = data.icon
          this.category.productUnit = data.productUnit
          this.category.parentCid = data.parentCid
          this.category.catLevel = data.catLevel
          this.category.sort = data.sort
          this.category.showStatus = data.showScore
        })
      },

      submitData () {
        if (this.dialogType === 'add') {
          this.addCategory()
        }
        if (this.dialogType === 'edit') {
          this.editCategory()
        }
      },

      editCategory () {
        const {catId, name, icon, productUnit} = this.category

        this.$http({
          url: this.$http.adornUrl(`/product/category/update`),
          method: 'post',
          data: this.$http.adornData({catId, name, icon, productUnit}/* ←只修改这几个字段 */, false)
        }).then(({data}) => {
          // 关闭对话框
          this.dialogVisible = false
          // 刷新菜单数据
          this.getMenus()
          // 设置需要默认展开的菜单
          this.expandedKey = [this.category.parentCid]
        })
      },

      append (data) {
        this.dialogType = 'add'
        this.title = '添加分类'
        this.dialogVisible = true
        this.category.parentCid = data.catId
        this.category.catLevel = data.catLevel * 1 + 1
        this.category.catId = null // 为null 才会让数据库以自增形式添加id
        this.category.icon = ''
        this.category.productUnit = ''
        this.category.sort = 0
        this.category.showStatus = 1
        this.category.name = ''
      },

      addCategory () {
        this.$http({
          url: this.$http.adornUrl('/product/category/save'),
          method: 'post',
          data: this.$http.adornData(this.category, false)
        }).then(({data}) => {
          this.$message({
            message: '菜单创建成功',
            type: 'success'
          })

          // 关闭对话框
          this.dialogVisible = false
          // 刷新菜单数据
          this.getMenus()
          // 设置需要默认展开的菜单
          this.expandedKey = [this.category.parentCid]
        })
      },

      remove (node, data) {
        const ids = [data.catId]
        this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            this.$message({
              message: '菜单删除成功',
              type: 'success'
            })

            // 刷新出新的菜单
            this.getMenus()
            // 设置需要默认展开的菜单
            this.expandedKey = [node.parent.data.catId]
          })
        })
          .catch(() => {

          })
      }
    },
    created () {
      this.getMenus()
    }
  }
</script>

<style scoped>

</style>
